#include <cstdio>
#include <cstddef>

#include <sys/time.h>

#include "timestamp.h"


TimeStamp::TimeStamp()
{
    this->m_ts = getCurrentTime();
}

TimeStamp::TimeStamp(unsigned int ts){
    this->m_ts = ts;
}

void TimeStamp::setNow(){
    this->m_ts = getCurrentTime();
}

static inline unsigned int tv2ts(struct timeval tv){
    unsigned int t;
    t = (tv.tv_sec % 86400) << 16;
    t |= tv.tv_usec / 1000;
    return t;
}

void TimeStamp::print(){
     printf("%02d:%02d:%02d:%03d\n",this->hour(), this->minute(), this->second(), this->millisecond());
}

void TimeStamp::print(const char* prompt){
     printf("%02d:%02d:%02d:%03d\t%s\n",this->hour(), this->minute(), this->second(), this->millisecond(), prompt);
}

unsigned int TimeStamp::getCurrentTime(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv2ts(tv);
}

TimeStamp* TimeStamp::now(){
    return new TimeStamp;
}

int TimeStamp::toMillisecond(){
    return (((this->hour()) * 60  + this->minute()) * 60 + this->second()) * 1000 + this->millisecond();
}

int TimeStamp::diff(TimeStamp x){
    int ms = this->toMillisecond();
    int msx = x.toMillisecond();
    return (ms - msx + 86400000) % 86400000;
}

int TimeStamp::diff(TimeStamp x, TimeStamp y){
    return x.diff(y);
}
